package com.myjavalab.objectpool;

import java.util.Vector;

public class ObjectPool {
	private int maxCount;
	private int minCount;
	private Class objectType;
	private int currentNum;
	private Object currentObj;
	private Vector pool;

	public ObjectPool(int maxCount, int minCount, Class objectType) {
		this.maxCount = maxCount;
		this.minCount = minCount;
		this.objectType = objectType;
		pool = new Vector();
	}

	public Object getObject() {
		if (currentNum == 0) {
			if (pool.size() < maxCount) {
				pool.add(new Object());
				currentObj = pool.get(0);
			}else {
				System.out.println("There is no available " + objectType);
				synchronized (this) {
					try{
						this.wait();
					}catch(Exception e) {
						System.out.println(e.getMessage());
						e.printStackTrace();
					}
				}
			}
		} else {
			currentObj = pool.get(0);
			currentNum--;
		}
		return currentObj;
	}
	
	public void returnObject(Object obj){
		if(obj.getClass().isInstance(objectType)){
			pool.addElement(obj);
			synchronized(this){
				notifyAll();
			}
		}else {
			throw new IllegalArgumentException("该对象池不能存放指定的对象类型");
		}
		
	}

}
